<html>
 <head>
  <meta charset="utf-8"/>
  <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"/>
  <title>
   Python下用Scrapy和MongoDB构建爬虫系统  | 数螺 | NAUT IDEA
  </title>
  <link href="http://cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" rel="stylesheet"/>
  <link href="http://cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
  <style type="text/css">
   #xmain img {
                  max-width: 100%;
                  display: block;
                  margin-top: 10px;
                  margin-bottom: 10px;
                }

                #xmain p {
                    line-height:150%;
                    font-size: 16px;
                    margin-top: 20px;
                }

                #xmain h2 {
                    font-size: 24px;
                }

                #xmain h3 {
                    font-size: 20px;
                }

                #xmain h4 {
                    font-size: 18px;
                }


                .header {
	           background-color: #0099ff;
	           color: #ffffff;
	           margin-bottom: 20px;
	        }

	        .header p {
                  margin: 0px;
                  padding: 10px 0;
                  display: inline-block;  
                  vertical-align: middle;
                  font-size: 16px;
               }

               .header a {
                 color: white;
               }

              .header img {
                 height: 25px;
              }
  </style>
  <script src="http://cdn.bootcss.com/jquery/3.0.0/jquery.min.js">
  </script>
  <script src="http://nautstatic-10007657.file.myqcloud.com/static/css/readability.min.js" type="text/javascript">
  </script>
  <script type="text/javascript">
   $(document).ready(function() {
                 var loc = document.location;
                 var uri = {
                  spec: "http://dataunion.org/16240.html",
                  host: "http://dataunion.org",
                  prePath: "http://dataunion.org",
                  scheme: "http",
                  pathBase: "http://dataunion.org/"
                 };
    
                 var documentClone = document.cloneNode(true);
                 var article = new Readability(uri, documentClone).parse();
     
                 document.getElementById("xmain").innerHTML = article.content;
                });
  </script>
  <!-- 1466459563: Accept with keywords: (title(0.4):Python,社区,系统,爬虫,数盟, topn(0.233333333333):社区,定义,数盟,蜘蛛,样板,工具,目录,文件,数据挖掘,Python,数据库,文档,开发者,文章,基础架构,方法,网页,用户,标题,问题,命令,链接,行业资讯,网站,数据,爬虫,列表,评论,选择器,页面).-->
 </head>
 <body onload="">
  <div class="header">
   <div class="container">
    <div class="row">
     <div class="col-xs-6 col-sm-6 text-left">
      <a href="/databee">
       <img src="http://nautidea-10007657.cos.myqcloud.com/logo_white.png"/>
      </a>
      <a href="/databee">
       <p>
        数螺
       </p>
      </a>
     </div>
     <div class="hidden-xs col-sm-6 text-right">
      <p>
       致力于数据科学的推广和知识传播
      </p>
     </div>
    </div>
   </div>
  </div>
  <div class="container text-center">
   <h1>
    Python下用Scrapy和MongoDB构建爬虫系统
   </h1>
  </div>
  <div class="container" id="xmain">
   ﻿﻿
   <title>
    Python下用Scrapy和MongoDB构建爬虫系统 | 数盟社区
   </title>
   <!-- All in One SEO Pack 2.2.7.6.2 by Michael Torbert of Semper Fi Web Design[32,75] -->
   <!-- /all in one seo pack -->
   <!--
<div align="center">
<a href="http://strata.oreilly.com.cn/hadoop-big-data-cn?cmp=mp-data-confreg-home-stcn16_dataunion_pc" target="_blank"><img src="http://dataunion.org/wp-content/uploads/2016/05/stratabj.jpg"/ ></a>
</div>
-->
   <header id="header-web">
    <div class="header-main">
     <hgroup class="logo">
      <h1>
       <a href="http://dataunion.org/" rel="home" title="数盟社区">
        <img src="http://dataunion.org/wp-content/themes/yzipi/images/logo.png"/>
       </a>
      </h1>
     </hgroup>
     <!--logo-->
     <nav class="header-nav">
      <ul class="menu" id="menu-%e4%b8%bb%e8%8f%9c%e5%8d%95">
       <li class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-has-children menu-item-71" id="menu-item-71">
        <a href="http://dataunion.org/category/events" title="events">
         活动
        </a>
        <ul class="sub-menu">
         <li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-22457" id="menu-item-22457">
          <a href="http://dataunion.org/2016timeline">
           2016档期
          </a>
         </li>
         <li class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-22459" id="menu-item-22459">
          <a href="http://dataunion.org/category/parterc">
           合作会议
          </a>
         </li>
        </ul>
       </li>
       <li class="menu-item menu-item-type-taxonomy menu-item-object-category current-post-ancestor current-menu-parent current-post-parent menu-item-has-children menu-item-20869" id="menu-item-20869">
        <a href="http://dataunion.org/category/tech" title="articles">
         文章
        </a>
        <ul class="sub-menu">
         <li class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-20867" id="menu-item-20867">
          <a href="http://dataunion.org/category/tech/base" title="base">
           基础架构
          </a>
         </li>
         <li class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-3302" id="menu-item-3302">
          <a href="http://dataunion.org/category/tech/ai" title="ai">
           人工智能
          </a>
         </li>
         <li class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-3303" id="menu-item-3303">
          <a href="http://dataunion.org/category/tech/analysis" title="analysis">
           数据分析
          </a>
         </li>
         <li class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-21920" id="menu-item-21920">
          <a href="http://dataunion.org/category/tech/dm">
           数据挖掘
          </a>
         </li>
         <li class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-3314" id="menu-item-3314">
          <a href="http://dataunion.org/category/tech/viz" title="viz">
           可视化
          </a>
         </li>
         <li class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-3305" id="menu-item-3305">
          <a href="http://dataunion.org/category/tech/devl" title="devl">
           编程语言
          </a>
         </li>
        </ul>
       </li>
       <li class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-has-children menu-item-20876" id="menu-item-20876">
        <a href="http://dataunion.org/category/industry">
         行业
        </a>
        <ul class="sub-menu">
         <li class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-16328" id="menu-item-16328">
          <a href="http://dataunion.org/category/industry/case" title="case">
           行业应用
          </a>
         </li>
         <li class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-2112" id="menu-item-2112">
          <a href="http://dataunion.org/category/industry/demo" title="demo">
           Demo展示
          </a>
         </li>
         <li class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-21562" id="menu-item-21562">
          <a href="http://dataunion.org/category/industry/news">
           行业资讯
          </a>
         </li>
        </ul>
       </li>
       <li class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-311" id="menu-item-311">
        <a href="http://dataunion.org/category/sources" title="sources">
         资源
        </a>
       </li>
       <li class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-20870" id="menu-item-20870">
        <a href="http://dataunion.org/category/books" title="book">
         图书
        </a>
       </li>
       <li class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-21363" id="menu-item-21363">
        <a href="http://dataunion.org/category/training">
         课程
        </a>
       </li>
       <li class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-has-children menu-item-21853" id="menu-item-21853">
        <a href="http://dataunion.org/category/jobs">
         职位
        </a>
        <ul class="sub-menu">
         <li class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-22050" id="menu-item-22050">
          <a href="http://dataunion.org/category/career">
           职业规划
          </a>
         </li>
        </ul>
       </li>
      </ul>
     </nav>
     <!--header-nav-->
    </div>
   </header>
   <!--header-web-->
   <div id="main">
    <div id="soutab">
     <form action="http://dataunion.org/" class="search" method="get">
     </form>
    </div>
    <div id="container">
     <nav id="mbx">
      当前位置：
      <a href="http://dataunion.org">
       首页
      </a>
      &gt;
      <a href="http://dataunion.org/category/tech">
       文章
      </a>
      &gt;  正文
     </nav>
     <!--mbx-->
     <article class="content">
      <header align="centre" class="contenttitle">
       <div class="mscc">
        <h1 class="mscctitle">
         <a href="http://dataunion.org/16240.html">
          Python下用Scrapy和MongoDB构建爬虫系统
         </a>
        </h1>
        <address class="msccaddress ">
         <em>
          2,302 次阅读 -
         </em>
         <a href="http://dataunion.org/category/tech" rel="category tag">
          文章
         </a>
        </address>
       </div>
      </header>
      <div class="content-text">
       <p>
        这篇文章将根据真实的兼职需求编写一个爬虫，用户想要一个Python程序从Stack Overflow抓取数据，获取新的问题（问题标题和URL）。抓取的数据应当存入MongoDB。值得注意的是，Stack Overflow已经提供了可用于读取同样数据的API。但是用户想要一个爬虫，那就给他一个爬虫。
       </p>
       <p>
        像往常一样，在开始任何抓取工作前，一定要先查看该网站的使用/服务条款，要尊重 robots.txt 文件。抓取行为应该遵守道德，不要在很短时间内发起大量请求，从而导致网站遭受泛洪攻击。对待那些你要抓取的网站，要像对待自己的一样。
       </p>
       <h2>
        安装
       </h2>
       <p>
        我们需要Scrapy库(v0.24.4)，以及用于在MongoDB中存储数据的PyMongo库(v2.7.2)。同样需要安装MongoDB。
       </p>
       <h3>
        Scrapy
       </h3>
       <p>
        如果使用OSX或某种Linux，使用pip安装Scrapy（激活命令行）：
       </p>
       <div>
        <div class="syntaxhighlighter notranslate python" id="highlighter_82455">
         <table border="0" cellpadding="0" cellspacing="0">
          <tbody>
           <tr>
            <td class="gutter">
             <div class="line number1 index0 alt2">
              1
             </div>
            </td>
            <td class="code">
             <div class="container">
              <div class="line number1 index0 alt2">
               <code class="python plain">
                $ pip install Scrapy
               </code>
              </div>
             </div>
            </td>
           </tr>
          </tbody>
         </table>
        </div>
       </div>
       <p>
        如果使用Windows的机器，你需要手动安装一堆依赖库（木羊吐槽：Win下也是有pip的po主你不要黑她，经测可以用上面命令直接安装成功）。请参考官方文档详细说明以及我创建的Youtube视频。
       </p>
       <p>
        一旦Scrapy安装完毕，可在Python命令行中使用这个命令验证：
        <code>
         <br/>
        </code>
       </p>
       <div>
        <div class="syntaxhighlighter notranslate python" id="highlighter_141312">
         <table border="0" cellpadding="0" cellspacing="0">
          <tbody>
           <tr>
            <td class="gutter">
             <div class="line number1 index0 alt2">
              1
             </div>
             <div class="line number2 index1 alt1">
              2
             </div>
            </td>
            <td class="code">
             <div class="container">
              <div class="line number1 index0 alt2">
               <code class="python plain">
                &gt;&gt;&gt;
               </code>
               <code class="python keyword">
                import
               </code>
               <code class="python plain">
                scrapy
               </code>
              </div>
              <div class="line number2 index1 alt1">
               <code class="python plain">
                &gt;&gt;&gt;
               </code>
              </div>
             </div>
            </td>
           </tr>
          </tbody>
         </table>
        </div>
       </div>
       <p>
        如果没有出错，安装就完成了。
       </p>
       <h3>
        PyMongo
       </h3>
       <p>
        下一步，使用pip安装PyMongo：
       </p>
       <div>
        <div class="syntaxhighlighter notranslate python" id="highlighter_862156">
         <table border="0" cellpadding="0" cellspacing="0">
          <tbody>
           <tr>
            <td class="gutter">
             <div class="line number1 index0 alt2">
              1
             </div>
            </td>
            <td class="code">
             <div class="container">
              <div class="line number1 index0 alt2">
               <code class="python plain">
                $ pip install pymongo
               </code>
              </div>
             </div>
            </td>
           </tr>
          </tbody>
         </table>
        </div>
       </div>
       <p>
        现在可以开始构建爬虫了。
       </p>
       <h2>
        Scrapy工程
       </h2>
       <p>
        先创建一个新的Scrapy工程：
       </p>
       <div>
        <div class="syntaxhighlighter notranslate python" id="highlighter_325033">
         <table border="0" cellpadding="0" cellspacing="0">
          <tbody>
           <tr>
            <td class="gutter">
             <div class="line number1 index0 alt2">
              1
             </div>
            </td>
            <td class="code">
             <div class="container">
              <div class="line number1 index0 alt2">
               <code class="python plain">
                $ scrapy startproject stack
               </code>
              </div>
             </div>
            </td>
           </tr>
          </tbody>
         </table>
        </div>
       </div>
       <p>
        这条命令创建了许多文件和文件夹，其中包含一套有助于你快速开始的基本模板：
        <code>
         <br/>
        </code>
       </p>
       <div>
        <div class="syntaxhighlighter notranslate text" id="highlighter_589957">
         <table border="0" cellpadding="0" cellspacing="0">
          <tbody>
           <tr>
            <td class="gutter">
             <div class="line number1 index0 alt2">
              1
             </div>
             <div class="line number2 index1 alt1">
              2
             </div>
             <div class="line number3 index2 alt2">
              3
             </div>
             <div class="line number4 index3 alt1">
              4
             </div>
             <div class="line number5 index4 alt2">
              5
             </div>
             <div class="line number6 index5 alt1">
              6
             </div>
             <div class="line number7 index6 alt2">
              7
             </div>
             <div class="line number8 index7 alt1">
              8
             </div>
            </td>
            <td class="code">
             <div class="container">
              <div class="line number1 index0 alt2">
               <code class="text plain">
                ├── scrapy.cfg
               </code>
              </div>
              <div class="line number2 index1 alt1">
               <code class="text plain">
                └── stack
               </code>
              </div>
              <div class="line number3 index2 alt2">
               <code class="text spaces">
               </code>
               <code class="text plain">
                ├── __init__.py
               </code>
              </div>
              <div class="line number4 index3 alt1">
               <code class="text spaces">
               </code>
               <code class="text plain">
                ├── items.py
               </code>
              </div>
              <div class="line number5 index4 alt2">
               <code class="text spaces">
               </code>
               <code class="text plain">
                ├── pipelines.py
               </code>
              </div>
              <div class="line number6 index5 alt1">
               <code class="text spaces">
               </code>
               <code class="text plain">
                ├── settings.py
               </code>
              </div>
              <div class="line number7 index6 alt2">
               <code class="text spaces">
               </code>
               <code class="text plain">
                └── spiders
               </code>
              </div>
              <div class="line number8 index7 alt1">
               <code class="text spaces">
               </code>
               <code class="text plain">
                └── __init__.py
               </code>
              </div>
             </div>
            </td>
           </tr>
          </tbody>
         </table>
        </div>
       </div>
       <h3>
        提取数据
       </h3>
       <p>
        items.py文件用于定义存储“容器”，用来存储将要抓取的数据。
       </p>
       <p>
        StackItem()类继承自Item (
        <a href="http://doc.scrapy.org/en/latest/topics/items.html" title="文档">
         文档
        </a>
        )，主要包含一些Scrapy已经为我们创建好的预定义对象：
       </p>
       <div>
        <div class="syntaxhighlighter notranslate python" id="highlighter_60183">
         <table border="0" cellpadding="0" cellspacing="0">
          <tbody>
           <tr>
            <td class="gutter">
             <div class="line number1 index0 alt2">
              1
             </div>
             <div class="line number2 index1 alt1">
              2
             </div>
             <div class="line number3 index2 alt2">
              3
             </div>
             <div class="line number4 index3 alt1">
              4
             </div>
             <div class="line number5 index4 alt2">
              5
             </div>
             <div class="line number6 index5 alt1">
              6
             </div>
            </td>
            <td class="code">
             <div class="container">
              <div class="line number1 index0 alt2">
               <code class="python keyword">
                import
               </code>
               <code class="python plain">
                scrapy
               </code>
              </div>
              <div class="line number2 index1 alt1">
              </div>
              <div class="line number3 index2 alt2">
               <code class="python keyword">
                class
               </code>
               <code class="python plain">
                StackItem(scrapy.Item):
               </code>
              </div>
              <div class="line number4 index3 alt1">
               <code class="python spaces">
               </code>
               <code class="python comments">
                # define the fields for your item here like:
               </code>
              </div>
              <div class="line number5 index4 alt2">
               <code class="python spaces">
               </code>
               <code class="python comments">
                # name = scrapy.Field()
               </code>
              </div>
              <div class="line number6 index5 alt1">
               <code class="python spaces">
               </code>
               <code class="python keyword">
                pass
               </code>
              </div>
             </div>
            </td>
           </tr>
          </tbody>
         </table>
        </div>
       </div>
       <p>
        添加一些想要收集的项。用户想要每条问题的标题和URL。那么，照这样更新items.py：
       </p>
       <div>
        <div class="syntaxhighlighter notranslate python" id="highlighter_497257">
         <table border="0" cellpadding="0" cellspacing="0">
          <tbody>
           <tr>
            <td class="gutter">
             <div class="line number1 index0 alt2">
              1
             </div>
             <div class="line number2 index1 alt1">
              2
             </div>
             <div class="line number3 index2 alt2">
              3
             </div>
             <div class="line number4 index3 alt1">
              4
             </div>
             <div class="line number5 index4 alt2">
              5
             </div>
            </td>
            <td class="code">
             <div class="container">
              <div class="line number1 index0 alt2">
               <code class="python keyword">
                from
               </code>
               <code class="python plain">
                scrapy.item
               </code>
               <code class="python keyword">
                import
               </code>
               <code class="python plain">
                Item, Field
               </code>
              </div>
              <div class="line number2 index1 alt1">
              </div>
              <div class="line number3 index2 alt2">
               <code class="python keyword">
                class
               </code>
               <code class="python plain">
                StackItem(Item):
               </code>
              </div>
              <div class="line number4 index3 alt1">
               <code class="python spaces">
               </code>
               <code class="python plain">
                title
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                Field()
               </code>
              </div>
              <div class="line number5 index4 alt2">
               <code class="python spaces">
               </code>
               <code class="python plain">
                url
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                Field()
               </code>
              </div>
             </div>
            </td>
           </tr>
          </tbody>
         </table>
        </div>
       </div>
       <h3>
        创建蜘蛛
       </h3>
       <p>
        在“spiders”目录下建立一个名为stack_spider.py的文件。这里是见证奇迹发生的地方—-比如在这里告诉Scrapy怎么去找到我们想要的指定数据。正如你想的那样，对于每一个独立的网页，stack_spider.py都是不同的。
       </p>
       <p>
        我们从定义一个类开始，这个类继承Scrapy的Spider，并添加一些必须的属性：
       </p>
       <div>
        <div class="syntaxhighlighter notranslate python" id="highlighter_590566">
         <table border="0" cellpadding="0" cellspacing="0">
          <tbody>
           <tr>
            <td class="gutter">
             <div class="line number1 index0 alt2">
              1
             </div>
             <div class="line number2 index1 alt1">
              2
             </div>
             <div class="line number3 index2 alt2">
              3
             </div>
             <div class="line number4 index3 alt1">
              4
             </div>
             <div class="line number5 index4 alt2">
              5
             </div>
             <div class="line number6 index5 alt1">
              6
             </div>
             <div class="line number7 index6 alt2">
              7
             </div>
             <div class="line number8 index7 alt1">
              8
             </div>
             <div class="line number9 index8 alt2">
              9
             </div>
            </td>
            <td class="code">
             <div class="container">
              <div class="line number1 index0 alt2">
               <code class="python keyword">
                from
               </code>
               <code class="python plain">
                scrapy
               </code>
               <code class="python keyword">
                import
               </code>
               <code class="python plain">
                Spider
               </code>
              </div>
              <div class="line number2 index1 alt1">
              </div>
              <div class="line number3 index2 alt2">
              </div>
              <div class="line number4 index3 alt1">
               <code class="python keyword">
                class
               </code>
               <code class="python plain">
                StackSpider(Spider):
               </code>
              </div>
              <div class="line number5 index4 alt2">
               <code class="python spaces">
               </code>
               <code class="python plain">
                name
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python string">
                "stack"
               </code>
              </div>
              <div class="line number6 index5 alt1">
               <code class="python spaces">
               </code>
               <code class="python plain">
                allowed_domains
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                [
               </code>
               <code class="python string">
                "stackoverflow.com"
               </code>
               <code class="python plain">
                ]
               </code>
              </div>
              <div class="line number7 index6 alt2">
               <code class="python spaces">
               </code>
               <code class="python plain">
                start_urls
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                [
               </code>
              </div>
              <div class="line number8 index7 alt1">
               <code class="python spaces">
               </code>
               <code class="python string">
                "http://stackoverflow.com/questions?pagesize=50&amp;sort=newest"
               </code>
               <code class="python plain">
                ,
               </code>
              </div>
              <div class="line number9 index8 alt2">
               <code class="python spaces">
               </code>
               <code class="python plain">
                ]
               </code>
              </div>
             </div>
            </td>
           </tr>
          </tbody>
         </table>
        </div>
       </div>
       <p>
        最初一些变量的含义很容易理解（
        <a href="http://doc.scrapy.org/en/latest/topics/spiders.html#spider" title="文档">
         文档
        </a>
        ）：
       </p>
       <ul>
        <li>
         定义蜘蛛的名字。
        </li>
        <li>
         <code>
          allowed_domains
         </code>
         包含构成许可域的基础URL，供蜘蛛去爬。
        </li>
        <li>
         <code>
          start_urls
         </code>
         是一个URL列表，蜘蛛从这里开始爬。蜘蛛从start_urls中的URL下载数据，所有后续的URL将从这些数据中获取。
        </li>
       </ul>
       <h3>
        XPath选择器
       </h3>
       <p>
        接下来，Scrapy使用XPath选择器在一个网站上提取数据。也就是说，我们可以通过一个给定的XPath选择HTML数据的特定部分。正如Scrapy所称，“XPath是一种选择XML节点的语言，也可以用于HTML。”
       </p>
       <p>
        使用Chrome的开发者工具，可以很容易找到一个特定的Xpath。简单地检查一个特定的HTML元素，复制XPath，然后修改（如有需要）。
       </p>
       <p>
        <img src="http://dataunion.org/wp-content/uploads/2015/04/6941baebjw1ereiat9x8vj20vr0iigsd.jpg"/>
       </p>
       <p>
        开发者工具同时为用户提供在JavaScript控制台测试XPath选择器的功能，使用$x，如
        <code>
         $x("//img")
        </code>
        :
       </p>
       <p>
        <img src="http://dataunion.org/wp-content/uploads/2015/04/6941baebjw1ereiar83n4j20wb0gqjvv.jpg"/>
       </p>
       <p>
        继续，通过定义的XPath告诉Scrapy去哪里寻找信息。在Chrom中导航至Stack Overflow网址，寻找XPath选择器。
       </p>
       <p>
        <img src="http://dataunion.org/wp-content/uploads/2015/04/6941baebjw1ereianq9n9j20pe0g979w.jpg"/>
       </p>
       <p>
        右键点击第一条问题，选择“插入元素”：
       </p>
       <p>
        现在从
        <code>
         &lt;div class="summary"&gt;, //*[@id="question-summary-27624141"]/div[2]
        </code>
        中抓取XPath，然后在JavaScript控制台测试它：
       </p>
       <p>
        <img src="http://dataunion.org/wp-content/uploads/2015/04/6941baebjw1ereiamke2yj20qu0ed78w.jpg"/>
       </p>
       <p>
        也许你会说，这只选择了一条问题。现在需要改变XPath去抓取所有的问题。有什么想法？很简单：
        <code>
         //div[@class="summary"]/h3
        </code>
        。
       </p>
       <p>
        什么意思呢？本质上，这条XPath是说：抓取
        <code>
         &lt;div&gt;
        </code>
        的子树中所有这一类
        <code>
         &lt;h3&gt;
        </code>
        元素的总集。在JavaScript控制台中测试XPath。
       </p>
       <p>
        请注意我们不会使用Chrome开发者工具的实际输出。在大多数案例中，这些输出仅仅是一个参考，便于直接找到能用的XPath。
       </p>
       <p>
        现在更新stack_spider.py脚本：
       </p>
       <div>
        <div class="syntaxhighlighter notranslate python" id="highlighter_470299">
         <table border="0" cellpadding="0" cellspacing="0">
          <tbody>
           <tr>
            <td class="gutter">
             <div class="line number1 index0 alt2">
              1
             </div>
             <div class="line number2 index1 alt1">
              2
             </div>
             <div class="line number3 index2 alt2">
              3
             </div>
             <div class="line number4 index3 alt1">
              4
             </div>
             <div class="line number5 index4 alt2">
              5
             </div>
             <div class="line number6 index5 alt1">
              6
             </div>
             <div class="line number7 index6 alt2">
              7
             </div>
             <div class="line number8 index7 alt1">
              8
             </div>
             <div class="line number9 index8 alt2">
              9
             </div>
             <div class="line number10 index9 alt1">
              10
             </div>
             <div class="line number11 index10 alt2">
              11
             </div>
             <div class="line number12 index11 alt1">
              12
             </div>
             <div class="line number13 index12 alt2">
              13
             </div>
            </td>
            <td class="code">
             <div class="container">
              <div class="line number1 index0 alt2">
               <code class="python keyword">
                from
               </code>
               <code class="python plain">
                scrapy
               </code>
               <code class="python keyword">
                import
               </code>
               <code class="python plain">
                Spider
               </code>
              </div>
              <div class="line number2 index1 alt1">
               <code class="python keyword">
                from
               </code>
               <code class="python plain">
                scrapy.selector
               </code>
               <code class="python keyword">
                import
               </code>
               <code class="python plain">
                Selector
               </code>
              </div>
              <div class="line number3 index2 alt2">
              </div>
              <div class="line number4 index3 alt1">
              </div>
              <div class="line number5 index4 alt2">
               <code class="python keyword">
                class
               </code>
               <code class="python plain">
                StackSpider(Spider):
               </code>
              </div>
              <div class="line number6 index5 alt1">
               <code class="python spaces">
               </code>
               <code class="python plain">
                name
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python string">
                "stack"
               </code>
              </div>
              <div class="line number7 index6 alt2">
               <code class="python spaces">
               </code>
               <code class="python plain">
                allowed_domains
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                [
               </code>
               <code class="python string">
                "stackoverflow.com"
               </code>
               <code class="python plain">
                ]
               </code>
              </div>
              <div class="line number8 index7 alt1">
               <code class="python spaces">
               </code>
               <code class="python plain">
                start_urls
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                [
               </code>
              </div>
              <div class="line number9 index8 alt2">
               <code class="python spaces">
               </code>
               <code class="python string">
                "http://stackoverflow.com/questions?pagesize=50&amp;sort=newest"
               </code>
               <code class="python plain">
                ,
               </code>
              </div>
              <div class="line number10 index9 alt1">
               <code class="python spaces">
               </code>
               <code class="python plain">
                ]
               </code>
              </div>
              <div class="line number11 index10 alt2">
              </div>
              <div class="line number12 index11 alt1">
               <code class="python spaces">
               </code>
               <code class="python keyword">
                def
               </code>
               <code class="python plain">
                parse(
               </code>
               <code class="python color1">
                self
               </code>
               <code class="python plain">
                , response):
               </code>
              </div>
              <div class="line number13 index12 alt2">
               <code class="python spaces">
               </code>
               <code class="python plain">
                questions
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                Selector(response).xpath(
               </code>
               <code class="python string">
                '//div[@class="summary"]/h3'
               </code>
               <code class="python plain">
                )
               </code>
              </div>
             </div>
            </td>
           </tr>
          </tbody>
         </table>
        </div>
       </div>
       <h3>
        提取数据
       </h3>
       <p>
        我们仍然需要解析和抓取想要的数据，它符合
        <code>
         &lt;div class="summary"&amp;gt&lt;h3&amp;gt
        </code>
        。继续，像这样更新stack_spider.py：
       </p>
       <div>
        <div class="syntaxhighlighter notranslate python" id="highlighter_847614">
         <table border="0" cellpadding="0" cellspacing="0">
          <tbody>
           <tr>
            <td class="gutter">
             <div class="line number1 index0 alt2">
              1
             </div>
             <div class="line number2 index1 alt1">
              2
             </div>
             <div class="line number3 index2 alt2">
              3
             </div>
             <div class="line number4 index3 alt1">
              4
             </div>
             <div class="line number5 index4 alt2">
              5
             </div>
             <div class="line number6 index5 alt1">
              6
             </div>
             <div class="line number7 index6 alt2">
              7
             </div>
             <div class="line number8 index7 alt1">
              8
             </div>
             <div class="line number9 index8 alt2">
              9
             </div>
             <div class="line number10 index9 alt1">
              10
             </div>
             <div class="line number11 index10 alt2">
              11
             </div>
             <div class="line number12 index11 alt1">
              12
             </div>
             <div class="line number13 index12 alt2">
              13
             </div>
             <div class="line number14 index13 alt1">
              14
             </div>
             <div class="line number15 index14 alt2">
              15
             </div>
             <div class="line number16 index15 alt1">
              16
             </div>
             <div class="line number17 index16 alt2">
              17
             </div>
             <div class="line number18 index17 alt1">
              18
             </div>
             <div class="line number19 index18 alt2">
              19
             </div>
             <div class="line number20 index19 alt1">
              20
             </div>
             <div class="line number21 index20 alt2">
              21
             </div>
             <div class="line number22 index21 alt1">
              22
             </div>
             <div class="line number23 index22 alt2">
              23
             </div>
            </td>
            <td class="code">
             <div class="container">
              <div class="line number1 index0 alt2">
               <code class="python keyword">
                from
               </code>
               <code class="python plain">
                scrapy
               </code>
               <code class="python keyword">
                import
               </code>
               <code class="python plain">
                Spider
               </code>
              </div>
              <div class="line number2 index1 alt1">
               <code class="python keyword">
                from
               </code>
               <code class="python plain">
                scrapy.selector
               </code>
               <code class="python keyword">
                import
               </code>
               <code class="python plain">
                Selector
               </code>
              </div>
              <div class="line number3 index2 alt2">
              </div>
              <div class="line number4 index3 alt1">
               <code class="python keyword">
                from
               </code>
               <code class="python plain">
                stack.items
               </code>
               <code class="python keyword">
                import
               </code>
               <code class="python plain">
                StackItem
               </code>
              </div>
              <div class="line number5 index4 alt2">
              </div>
              <div class="line number6 index5 alt1">
              </div>
              <div class="line number7 index6 alt2">
               <code class="python keyword">
                class
               </code>
               <code class="python plain">
                StackSpider(Spider):
               </code>
              </div>
              <div class="line number8 index7 alt1">
               <code class="python spaces">
               </code>
               <code class="python plain">
                name
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python string">
                "stack"
               </code>
              </div>
              <div class="line number9 index8 alt2">
               <code class="python spaces">
               </code>
               <code class="python plain">
                allowed_domains
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                [
               </code>
               <code class="python string">
                "stackoverflow.com"
               </code>
               <code class="python plain">
                ]
               </code>
              </div>
              <div class="line number10 index9 alt1">
               <code class="python spaces">
               </code>
               <code class="python plain">
                start_urls
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                [
               </code>
              </div>
              <div class="line number11 index10 alt2">
               <code class="python spaces">
               </code>
               <code class="python string">
                "http://stackoverflow.com/questions?pagesize=50&amp;sort=newest"
               </code>
               <code class="python plain">
                ,
               </code>
              </div>
              <div class="line number12 index11 alt1">
               <code class="python spaces">
               </code>
               <code class="python plain">
                ]
               </code>
              </div>
              <div class="line number13 index12 alt2">
              </div>
              <div class="line number14 index13 alt1">
               <code class="python spaces">
               </code>
               <code class="python keyword">
                def
               </code>
               <code class="python plain">
                parse(
               </code>
               <code class="python color1">
                self
               </code>
               <code class="python plain">
                , response):
               </code>
              </div>
              <div class="line number15 index14 alt2">
               <code class="python spaces">
               </code>
               <code class="python plain">
                questions
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                Selector(response).xpath(
               </code>
               <code class="python string">
                '//div[@class="summary"]/h3'
               </code>
               <code class="python plain">
                )
               </code>
              </div>
              <div class="line number16 index15 alt1">
              </div>
              <div class="line number17 index16 alt2">
               <code class="python spaces">
               </code>
               <code class="python keyword">
                for
               </code>
               <code class="python plain">
                question
               </code>
               <code class="python keyword">
                in
               </code>
               <code class="python plain">
                questions:
               </code>
              </div>
              <div class="line number18 index17 alt1">
               <code class="python spaces">
               </code>
               <code class="python plain">
                item
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                StackItem()
               </code>
              </div>
              <div class="line number19 index18 alt2">
               <code class="python spaces">
               </code>
               <code class="python plain">
                item[
               </code>
               <code class="python string">
                'title'
               </code>
               <code class="python plain">
                ]
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                question.xpath(
               </code>
              </div>
              <div class="line number20 index19 alt1">
               <code class="python spaces">
               </code>
               <code class="python string">
                'a[@class="question-hyperlink"]/text()'
               </code>
               <code class="python plain">
                ).extract()[
               </code>
               <code class="python value">
                0
               </code>
               <code class="python plain">
                ]
               </code>
              </div>
              <div class="line number21 index20 alt2">
               <code class="python spaces">
               </code>
               <code class="python plain">
                item[
               </code>
               <code class="python string">
                'url'
               </code>
               <code class="python plain">
                ]
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                question.xpath(
               </code>
              </div>
              <div class="line number22 index21 alt1">
               <code class="python spaces">
               </code>
               <code class="python string">
                'a[@class="question-hyperlink"]/@href'
               </code>
               <code class="python plain">
                ).extract()[
               </code>
               <code class="python value">
                0
               </code>
               <code class="python plain">
                ]
               </code>
              </div>
              <div class="line number23 index22 alt2">
               <code class="python spaces">
               </code>
               <code class="python keyword">
                yield
               </code>
               <code class="python plain">
                item
               </code>
              </div>
             </div>
            </td>
           </tr>
          </tbody>
         </table>
        </div>
       </div>
       <p>
        我们将遍历问题，从抓取的数据中分配标题和URL的值。一定要利用Chrome开发者工具的JavaScript控制台测试XPath的选择器，例如
        <code>
         $x('//div[@class="summary"]/h3/a[@class="question-hyperlink"]/text()')
        </code>
        和
        <code>
         $x('//div[@class="summary"]/h3/a[@class="question-hyperlink"]/@href')
        </code>
        。
       </p>
       <h2>
        测试
       </h2>
       <p>
        准备好第一次测试了吗？只要简单地在“stack”目录中运行下面命令：
        <code>
         <br/>
        </code>
       </p>
       <div>
        <div class="syntaxhighlighter notranslate text" id="highlighter_652040">
         <table border="0" cellpadding="0" cellspacing="0">
          <tbody>
           <tr>
            <td class="gutter">
             <div class="line number1 index0 alt2">
              1
             </div>
            </td>
            <td class="code">
             <div class="container">
              <div class="line number1 index0 alt2">
               <code class="text plain">
                $ scrapy crawl stack
               </code>
              </div>
             </div>
            </td>
           </tr>
          </tbody>
         </table>
        </div>
       </div>
       <p>
        随着Scrapy堆栈跟踪，你应该看到50条问题的标题和URL输出。你可以用下面这条小命令输出一个JSON文件：
        <code>
         <br/>
        </code>
       </p>
       <div>
        <div class="syntaxhighlighter notranslate python" id="highlighter_670451">
         <table border="0" cellpadding="0" cellspacing="0">
          <tbody>
           <tr>
            <td class="gutter">
             <div class="line number1 index0 alt2">
              1
             </div>
            </td>
            <td class="code">
             <div class="container">
              <div class="line number1 index0 alt2">
               <code class="python plain">
                $ scrapy crawl stack
               </code>
               <code class="python keyword">
                -
               </code>
               <code class="python plain">
                o items.json
               </code>
               <code class="python keyword">
                -
               </code>
               <code class="python plain">
                t json
               </code>
              </div>
             </div>
            </td>
           </tr>
          </tbody>
         </table>
        </div>
       </div>
       <p>
        我们已经基于要寻找的数据实现了爬虫。现在需要将抓取的数据存入MongoDB。
       </p>
       <h2>
        在MongoDB中存储数据
       </h2>
       <p>
        每当有一项返回，我们想验证数据，然后添加进一个Mongo集合。
       </p>
       <p>
        第一步是创建一个我们计划用来保存所有抓取数据的数据库。打开settings.py，指定管道然后加入数据库设置：
        <br/>
        <code>
        </code>
       </p>
       <div>
        <div class="syntaxhighlighter notranslate text" id="highlighter_86623">
         <table border="0" cellpadding="0" cellspacing="0">
          <tbody>
           <tr>
            <td class="gutter">
             <div class="line number1 index0 alt2">
              1
             </div>
             <div class="line number2 index1 alt1">
              2
             </div>
             <div class="line number3 index2 alt2">
              3
             </div>
             <div class="line number4 index3 alt1">
              4
             </div>
             <div class="line number5 index4 alt2">
              5
             </div>
             <div class="line number6 index5 alt1">
              6
             </div>
            </td>
            <td class="code">
             <div class="container">
              <div class="line number1 index0 alt2">
               <code class="text plain">
                ITEM_PIPELINES = ['stack.pipelines.MongoDBPipeline', ]
               </code>
              </div>
              <div class="line number2 index1 alt1">
              </div>
              <div class="line number3 index2 alt2">
               <code class="text plain">
                MONGODB_SERVER = "localhost"
               </code>
              </div>
              <div class="line number4 index3 alt1">
               <code class="text plain">
                MONGODB_PORT = 27017
               </code>
              </div>
              <div class="line number5 index4 alt2">
               <code class="text plain">
                MONGODB_DB = "stackoverflow"
               </code>
              </div>
              <div class="line number6 index5 alt1">
               <code class="text plain">
                MONGODB_COLLECTION = "questions"
               </code>
              </div>
             </div>
            </td>
           </tr>
          </tbody>
         </table>
        </div>
       </div>
       <p>
        管道管理
       </p>
       <p>
        我们建立了爬虫去抓取和解析HTML，而且已经设置了数据库配置。现在要在pipelines.py中通过一个管道连接两个部分。
       </p>
       <p>
        连接数据库
       </p>
       <p>
        首先，让我们定义一个函数去连接数据库：
       </p>
       <div>
        <div class="syntaxhighlighter notranslate python" id="highlighter_94100">
         <table border="0" cellpadding="0" cellspacing="0">
          <tbody>
           <tr>
            <td class="gutter">
             <div class="line number1 index0 alt2">
              1
             </div>
             <div class="line number2 index1 alt1">
              2
             </div>
             <div class="line number3 index2 alt2">
              3
             </div>
             <div class="line number4 index3 alt1">
              4
             </div>
             <div class="line number5 index4 alt2">
              5
             </div>
             <div class="line number6 index5 alt1">
              6
             </div>
             <div class="line number7 index6 alt2">
              7
             </div>
             <div class="line number8 index7 alt1">
              8
             </div>
             <div class="line number9 index8 alt2">
              9
             </div>
             <div class="line number10 index9 alt1">
              10
             </div>
             <div class="line number11 index10 alt2">
              11
             </div>
             <div class="line number12 index11 alt1">
              12
             </div>
             <div class="line number13 index12 alt2">
              13
             </div>
             <div class="line number14 index13 alt1">
              14
             </div>
            </td>
            <td class="code">
             <div class="container">
              <div class="line number1 index0 alt2">
               <code class="python keyword">
                import
               </code>
               <code class="python plain">
                pymongo
               </code>
              </div>
              <div class="line number2 index1 alt1">
              </div>
              <div class="line number3 index2 alt2">
               <code class="python keyword">
                from
               </code>
               <code class="python plain">
                scrapy.conf
               </code>
               <code class="python keyword">
                import
               </code>
               <code class="python plain">
                settings
               </code>
              </div>
              <div class="line number4 index3 alt1">
              </div>
              <div class="line number5 index4 alt2">
              </div>
              <div class="line number6 index5 alt1">
               <code class="python keyword">
                class
               </code>
               <code class="python plain">
                MongoDBPipeline(
               </code>
               <code class="python functions">
                object
               </code>
               <code class="python plain">
                ):
               </code>
              </div>
              <div class="line number7 index6 alt2">
              </div>
              <div class="line number8 index7 alt1">
               <code class="python spaces">
               </code>
               <code class="python keyword">
                def
               </code>
               <code class="python plain">
                __init__(
               </code>
               <code class="python color1">
                self
               </code>
               <code class="python plain">
                ):
               </code>
              </div>
              <div class="line number9 index8 alt2">
               <code class="python spaces">
               </code>
               <code class="python plain">
                connection
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                pymongo.Connection(
               </code>
              </div>
              <div class="line number10 index9 alt1">
               <code class="python spaces">
               </code>
               <code class="python plain">
                settings[
               </code>
               <code class="python string">
                'MONGODB_SERVER'
               </code>
               <code class="python plain">
                ],
               </code>
              </div>
              <div class="line number11 index10 alt2">
               <code class="python spaces">
               </code>
               <code class="python plain">
                settings[
               </code>
               <code class="python string">
                'MONGODB_PORT'
               </code>
               <code class="python plain">
                ]
               </code>
              </div>
              <div class="line number12 index11 alt1">
               <code class="python spaces">
               </code>
               <code class="python plain">
                )
               </code>
              </div>
              <div class="line number13 index12 alt2">
               <code class="python spaces">
               </code>
               <code class="python plain">
                db
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                connection[settings[
               </code>
               <code class="python string">
                'MONGODB_DB'
               </code>
               <code class="python plain">
                ]]
               </code>
              </div>
              <div class="line number14 index13 alt1">
               <code class="python spaces">
               </code>
               <code class="python color1">
                self
               </code>
               <code class="python plain">
                .collection
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                db[settings[
               </code>
               <code class="python string">
                'MONGODB_COLLECTION'
               </code>
               <code class="python plain">
                ]]
               </code>
              </div>
             </div>
            </td>
           </tr>
          </tbody>
         </table>
        </div>
       </div>
       <p>
        这里，我们创建一个类，MongoDBPipeline()，我们有一个构造函数初始化类，它定义Mongo的设置然后连接数据库。
       </p>
       <p>
        处理数据
       </p>
       <p>
        下一步，我们需要定义一个函数去处理被解析的数据：
       </p>
       <div>
        <div class="syntaxhighlighter notranslate python" id="highlighter_694396">
         <table border="0" cellpadding="0" cellspacing="0">
          <tbody>
           <tr>
            <td class="gutter">
             <div class="line number1 index0 alt2">
              1
             </div>
             <div class="line number2 index1 alt1">
              2
             </div>
             <div class="line number3 index2 alt2">
              3
             </div>
             <div class="line number4 index3 alt1">
              4
             </div>
             <div class="line number5 index4 alt2">
              5
             </div>
             <div class="line number6 index5 alt1">
              6
             </div>
             <div class="line number7 index6 alt2">
              7
             </div>
             <div class="line number8 index7 alt1">
              8
             </div>
             <div class="line number9 index8 alt2">
              9
             </div>
             <div class="line number10 index9 alt1">
              10
             </div>
             <div class="line number11 index10 alt2">
              11
             </div>
             <div class="line number12 index11 alt1">
              12
             </div>
             <div class="line number13 index12 alt2">
              13
             </div>
             <div class="line number14 index13 alt1">
              14
             </div>
             <div class="line number15 index14 alt2">
              15
             </div>
             <div class="line number16 index15 alt1">
              16
             </div>
             <div class="line number17 index16 alt2">
              17
             </div>
             <div class="line number18 index17 alt1">
              18
             </div>
             <div class="line number19 index18 alt2">
              19
             </div>
             <div class="line number20 index19 alt1">
              20
             </div>
             <div class="line number21 index20 alt2">
              21
             </div>
             <div class="line number22 index21 alt1">
              22
             </div>
             <div class="line number23 index22 alt2">
              23
             </div>
             <div class="line number24 index23 alt1">
              24
             </div>
             <div class="line number25 index24 alt2">
              25
             </div>
             <div class="line number26 index25 alt1">
              26
             </div>
             <div class="line number27 index26 alt2">
              27
             </div>
             <div class="line number28 index27 alt1">
              28
             </div>
            </td>
            <td class="code">
             <div class="container">
              <div class="line number1 index0 alt2">
               <code class="python keyword">
                import
               </code>
               <code class="python plain">
                pymongo
               </code>
              </div>
              <div class="line number2 index1 alt1">
              </div>
              <div class="line number3 index2 alt2">
               <code class="python keyword">
                from
               </code>
               <code class="python plain">
                scrapy.conf
               </code>
               <code class="python keyword">
                import
               </code>
               <code class="python plain">
                settings
               </code>
              </div>
              <div class="line number4 index3 alt1">
               <code class="python keyword">
                from
               </code>
               <code class="python plain">
                scrapy.exceptions
               </code>
               <code class="python keyword">
                import
               </code>
               <code class="python plain">
                DropItem
               </code>
              </div>
              <div class="line number5 index4 alt2">
               <code class="python keyword">
                from
               </code>
               <code class="python plain">
                scrapy
               </code>
               <code class="python keyword">
                import
               </code>
               <code class="python plain">
                log
               </code>
              </div>
              <div class="line number6 index5 alt1">
              </div>
              <div class="line number7 index6 alt2">
              </div>
              <div class="line number8 index7 alt1">
               <code class="python keyword">
                class
               </code>
               <code class="python plain">
                MongoDBPipeline(
               </code>
               <code class="python functions">
                object
               </code>
               <code class="python plain">
                ):
               </code>
              </div>
              <div class="line number9 index8 alt2">
              </div>
              <div class="line number10 index9 alt1">
               <code class="python spaces">
               </code>
               <code class="python keyword">
                def
               </code>
               <code class="python plain">
                __init__(
               </code>
               <code class="python color1">
                self
               </code>
               <code class="python plain">
                ):
               </code>
              </div>
              <div class="line number11 index10 alt2">
               <code class="python spaces">
               </code>
               <code class="python plain">
                connection
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                pymongo.Connection(
               </code>
              </div>
              <div class="line number12 index11 alt1">
               <code class="python spaces">
               </code>
               <code class="python plain">
                settings[
               </code>
               <code class="python string">
                'MONGODB_SERVER'
               </code>
               <code class="python plain">
                ],
               </code>
              </div>
              <div class="line number13 index12 alt2">
               <code class="python spaces">
               </code>
               <code class="python plain">
                settings[
               </code>
               <code class="python string">
                'MONGODB_PORT'
               </code>
               <code class="python plain">
                ]
               </code>
              </div>
              <div class="line number14 index13 alt1">
               <code class="python spaces">
               </code>
               <code class="python plain">
                )
               </code>
              </div>
              <div class="line number15 index14 alt2">
               <code class="python spaces">
               </code>
               <code class="python plain">
                db
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                connection[settings[
               </code>
               <code class="python string">
                'MONGODB_DB'
               </code>
               <code class="python plain">
                ]]
               </code>
              </div>
              <div class="line number16 index15 alt1">
               <code class="python spaces">
               </code>
               <code class="python color1">
                self
               </code>
               <code class="python plain">
                .collection
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                db[settings[
               </code>
               <code class="python string">
                'MONGODB_COLLECTION'
               </code>
               <code class="python plain">
                ]]
               </code>
              </div>
              <div class="line number17 index16 alt2">
              </div>
              <div class="line number18 index17 alt1">
               <code class="python spaces">
               </code>
               <code class="python keyword">
                def
               </code>
               <code class="python plain">
                process_item(
               </code>
               <code class="python color1">
                self
               </code>
               <code class="python plain">
                , item, spider):
               </code>
              </div>
              <div class="line number19 index18 alt2">
               <code class="python spaces">
               </code>
               <code class="python plain">
                valid
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python color1">
                True
               </code>
              </div>
              <div class="line number20 index19 alt1">
               <code class="python spaces">
               </code>
               <code class="python keyword">
                for
               </code>
               <code class="python plain">
                data
               </code>
               <code class="python keyword">
                in
               </code>
               <code class="python plain">
                item:
               </code>
              </div>
              <div class="line number21 index20 alt2">
               <code class="python spaces">
               </code>
               <code class="python keyword">
                if
               </code>
               <code class="python keyword">
                not
               </code>
               <code class="python plain">
                data:
               </code>
              </div>
              <div class="line number22 index21 alt1">
               <code class="python spaces">
               </code>
               <code class="python plain">
                valid
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python color1">
                False
               </code>
              </div>
              <div class="line number23 index22 alt2">
               <code class="python spaces">
               </code>
               <code class="python keyword">
                raise
               </code>
               <code class="python plain">
                DropItem(
               </code>
               <code class="python string">
                "Missing {0}!"
               </code>
               <code class="python plain">
                .
               </code>
               <code class="python functions">
                format
               </code>
               <code class="python plain">
                (data))
               </code>
              </div>
              <div class="line number24 index23 alt1">
               <code class="python spaces">
               </code>
               <code class="python keyword">
                if
               </code>
               <code class="python plain">
                valid:
               </code>
              </div>
              <div class="line number25 index24 alt2">
               <code class="python spaces">
               </code>
               <code class="python color1">
                self
               </code>
               <code class="python plain">
                .collection.insert(
               </code>
               <code class="python functions">
                dict
               </code>
               <code class="python plain">
                (item))
               </code>
              </div>
              <div class="line number26 index25 alt1">
               <code class="python spaces">
               </code>
               <code class="python plain">
                log.msg(
               </code>
               <code class="python string">
                "Question added to MongoDB database!"
               </code>
               <code class="python plain">
                ,
               </code>
              </div>
              <div class="line number27 index26 alt2">
               <code class="python spaces">
               </code>
               <code class="python plain">
                level
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                log.DEBUG, spider
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                spider)
               </code>
              </div>
              <div class="line number28 index27 alt1">
               <code class="python spaces">
               </code>
               <code class="python keyword">
                return
               </code>
               <code class="python plain">
                item
               </code>
              </div>
             </div>
            </td>
           </tr>
          </tbody>
         </table>
        </div>
       </div>
       <p>
        我们建立一个数据库连接，解包数据，然后将它存入数据库。现在再测试一次！
       </p>
       <h2>
        测试
       </h2>
       <p>
        再次，在“stack”目录下运行下面命令：
        <code>
         <br/>
        </code>
       </p>
       <div>
        <div class="syntaxhighlighter notranslate python" id="highlighter_684515">
         <table border="0" cellpadding="0" cellspacing="0">
          <tbody>
           <tr>
            <td class="gutter">
             <div class="line number1 index0 alt2">
              1
             </div>
            </td>
            <td class="code">
             <div class="container">
              <div class="line number1 index0 alt2">
               <code class="python plain">
                $ scrapy crawl stack
               </code>
              </div>
             </div>
            </td>
           </tr>
          </tbody>
         </table>
        </div>
       </div>
       <p>
        万岁！我们已经成功将我们爬下了的数据存入数据库：
       </p>
       <p>
        <img src="http://dataunion.org/wp-content/uploads/2015/04/6941baebjw1ereialc955j20xd0klanz.jpg"/>
       </p>
       <h2>
        总结
       </h2>
       <p>
        这是一个用Scrapy爬取网页的简单示例。真实兼职工作需要能跟踪分页链接的脚本，用CrawlSpider（
        <a href="http://doc.scrapy.org/en/latest/topics/spiders.html#crawlspider">
         文档
        </a>
        ）抓取每一个页面，非常容易实现。自己动手实现下，在下面Github仓库链接中写一个评论，快速查看代码。需要帮助？从
        <a href="https://github.com/realpython/stack-spider/blob/part1/stack/stack/spiders/stack_crawl.py">
         这个
        </a>
        脚本开始，它已经很接近完成了。然后查看第二部分，它包含完整的解决方案。
       </p>
       <hr/>
       <p>
        上文中，它可以从StackOverflow上下载最新的问题，并将它们存储在MongoDB数据库中。在本文中，我们将对其扩展，使它能够爬取每个网页底部的分页链接，并从每一页中下载问题（包含问题标题和URL）。
       </p>
       <p>
        在你开始任何爬取工作之前，检查目标网站的使用条款并遵守robots.txt文件。同时，做爬取练习时遵守道德，不要在短时间内向某个网站发起大量请求。像对待自己的网站一样对待任何你将爬取的网站。
       </p>
       <h2>
        开始
       </h2>
       <p>
        有两种可能的方法来接着从上次我们停下的地方继续进行。
       </p>
       <p>
        第一个方法是，扩展我们现有的网络爬虫，通过利用一个xpath表达式从”parse_item”方法里的响应中提取每个下一页链接，并通过回调同一个parse_item方法产生一个请求对象。利用这种方法，爬虫会自动生成针对我们指定的链接的新请求，你可以在
        <a href="http://doc.scrapy.org/en/latest/topics/spiders.html#spiders" target="_blank">
         Scrapy文档
        </a>
        这里找到更多有关该方法的信息。
       </p>
       <p>
        另一个更简单的方法是，使用一个不同类型的爬虫—CrawlSpider（
        <a href="http://doc.scrapy.org/en/latest/topics/spiders.html#crawlspider" target="_blank">
         链接
        </a>
        ）。这是基本Spider的一个扩展版本，它刚好满足我们的要求。
       </p>
       <h2>
        CrawlSpider
       </h2>
       <p>
        我们将使用与上一篇教程中相同的爬虫项目，所以如果你需要的话可以从repo上获取这些代码。
       </p>
       <h3>
        创建样板
       </h3>
       <p>
        在“stack”目录中，首先由crawl模板
        <a href="http://doc.scrapy.org/en/latest/topics/commands.html#std:command-genspider" target="_blank">
         生成
        </a>
        爬虫样板。
       </p>
       <div>
        <div class="syntaxhighlighter notranslate shell" id="highlighter_20443">
         <table border="0" cellpadding="0" cellspacing="0">
          <tbody>
           <tr>
            <td class="gutter">
             <div class="line number1 index0 alt2">
              1
             </div>
             <div class="line number2 index1 alt1">
              2
             </div>
             <div class="line number3 index2 alt2">
              3
             </div>
            </td>
            <td class="code">
             <div class="container">
              <div class="line number1 index0 alt2">
               <code class="shell plain">
                $ scrapy genspider stack_crawler  stackoverflow.com -t crawl
               </code>
              </div>
              <div class="line number2 index1 alt1">
               <code class="shell plain">
                Created spider
               </code>
               <code class="shell string">
                'stack_crawler'
               </code>
               <code class="shell plain">
                using template
               </code>
               <code class="shell string">
                'crawl'
               </code>
               <code class="shell keyword">
                in
               </code>
               <code class="shell plain">
                module:
               </code>
              </div>
              <div class="line number3 index2 alt2">
               <code class="shell spaces">
               </code>
               <code class="shell plain">
                stack.spiders.stack_crawler
               </code>
              </div>
             </div>
            </td>
           </tr>
          </tbody>
         </table>
        </div>
       </div>
       <p>
        Scrapy项目现在看起来应该像这样:
       </p>
       <div>
        <div class="syntaxhighlighter notranslate html" id="highlighter_856421">
         <table border="0" cellpadding="0" cellspacing="0">
          <tbody>
           <tr>
            <td class="gutter">
             <div class="line number1 index0 alt2">
              1
             </div>
             <div class="line number2 index1 alt1">
              2
             </div>
             <div class="line number3 index2 alt2">
              3
             </div>
             <div class="line number4 index3 alt1">
              4
             </div>
             <div class="line number5 index4 alt2">
              5
             </div>
             <div class="line number6 index5 alt1">
              6
             </div>
             <div class="line number7 index6 alt2">
              7
             </div>
             <div class="line number8 index7 alt1">
              8
             </div>
             <div class="line number9 index8 alt2">
              9
             </div>
             <div class="line number10 index9 alt1">
              10
             </div>
            </td>
            <td class="code">
             <div class="container">
              <div class="line number1 index0 alt2">
               <code class="html plain">
                ├── scrapy.cfg
               </code>
              </div>
              <div class="line number2 index1 alt1">
               <code class="html plain">
                └── stack
               </code>
              </div>
              <div class="line number3 index2 alt2">
               <code class="html spaces">
               </code>
               <code class="html plain">
                ├── __init__.py
               </code>
              </div>
              <div class="line number4 index3 alt1">
               <code class="html spaces">
               </code>
               <code class="html plain">
                ├── items.py
               </code>
              </div>
              <div class="line number5 index4 alt2">
               <code class="html spaces">
               </code>
               <code class="html plain">
                ├── pipelines.py
               </code>
              </div>
              <div class="line number6 index5 alt1">
               <code class="html spaces">
               </code>
               <code class="html plain">
                ├── settings.py
               </code>
              </div>
              <div class="line number7 index6 alt2">
               <code class="html spaces">
               </code>
               <code class="html plain">
                └── spiders
               </code>
              </div>
              <div class="line number8 index7 alt1">
               <code class="html spaces">
               </code>
               <code class="html plain">
                ├── __init__.py
               </code>
              </div>
              <div class="line number9 index8 alt2">
               <code class="html spaces">
               </code>
               <code class="html plain">
                ├── stack_crawler.py
               </code>
              </div>
              <div class="line number10 index9 alt1">
               <code class="html spaces">
               </code>
               <code class="html plain">
                └── stack_spider.py
               </code>
              </div>
             </div>
            </td>
           </tr>
          </tbody>
         </table>
        </div>
       </div>
       <p>
        stack_crawler.py文件内容如下：
       </p>
       <div>
        <div class="syntaxhighlighter notranslate python" id="highlighter_965629">
         <table border="0" cellpadding="0" cellspacing="0">
          <tbody>
           <tr>
            <td class="gutter">
             <div class="line number1 index0 alt2">
             </div>
            </td>
            <td class="code">
             <div class="container">
              <div class="line number1 index0 alt2">
               <code class="python comments">
                # -*- coding: utf-8 -*-
               </code>
              </div>
              <div class="line number2 index1 alt1">
               <code class="python keyword">
                import
               </code>
               <code class="python plain">
                scrapy
               </code>
              </div>
              <div class="line number3 index2 alt2">
               <code class="python keyword">
                from
               </code>
               <code class="python plain">
                scrapy.contrib.linkextractors
               </code>
               <code class="python keyword">
                import
               </code>
               <code class="python plain">
                LinkExtractor
               </code>
              </div>
              <div class="line number4 index3 alt1">
               <code class="python keyword">
                from
               </code>
               <code class="python plain">
                scrapy.contrib.spiders
               </code>
               <code class="python keyword">
                import
               </code>
               <code class="python plain">
                CrawlSpider, Rule
               </code>
              </div>
              <div class="line number5 index4 alt2">
              </div>
              <div class="line number6 index5 alt1">
               <code class="python keyword">
                from
               </code>
               <code class="python plain">
                stack.items
               </code>
               <code class="python keyword">
                import
               </code>
               <code class="python plain">
                StackItem
               </code>
              </div>
              <div class="line number7 index6 alt2">
              </div>
              <div class="line number8 index7 alt1">
               <code class="python keyword">
                class
               </code>
               <code class="python plain">
                StackCrawlerSpider(CrawlSpider):
               </code>
              </div>
              <div class="line number9 index8 alt2">
               <code class="python spaces">
               </code>
               <code class="python plain">
                name
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python string">
                'stack_crawler'
               </code>
              </div>
              <div class="line number10 index9 alt1">
               <code class="python spaces">
               </code>
               <code class="python plain">
                allowed_domains
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                [
               </code>
               <code class="python string">
                'stackoverflow.com'
               </code>
               <code class="python plain">
                ]
               </code>
              </div>
              <div class="line number11 index10 alt2">
               <code class="python spaces">
               </code>
               <code class="python plain">
                start_urls
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                [
               </code>
               <code class="python string">
                'http://www.stackoverflow.com/'
               </code>
               <code class="python plain">
                ]
               </code>
              </div>
              <div class="line number12 index11 alt1">
              </div>
              <div class="line number13 index12 alt2">
               <code class="python spaces">
               </code>
               <code class="python plain">
                rules
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                (
               </code>
              </div>
              <div class="line number14 index13 alt1">
               <code class="python spaces">
               </code>
               <code class="python plain">
                Rule(LinkExtractor(allow
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                r
               </code>
               <code class="python string">
                'Items/'
               </code>
               <code class="python plain">
                ), callback
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python string">
                'parse_item'
               </code>
               <code class="python plain">
                , follow
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python color1">
                True
               </code>
               <code class="python plain">
                ),
               </code>
              </div>
              <div class="line number15 index14 alt2">
               <code class="python spaces">
               </code>
               <code class="python plain">
                )
               </code>
              </div>
              <div class="line number16 index15 alt1">
              </div>
              <div class="line number17 index16 alt2">
               <code class="python spaces">
               </code>
               <code class="python keyword">
                def
               </code>
               <code class="python plain">
                parse_item(
               </code>
               <code class="python color1">
                self
               </code>
               <code class="python plain">
                , response):
               </code>
              </div>
              <div class="line number18 index17 alt1">
               <code class="python spaces">
               </code>
               <code class="python plain">
                i
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                StackItem()
               </code>
              </div>
              <div class="line number19 index18 alt2">
               <code class="python spaces">
               </code>
               <code class="python comments">
                #i['domain_id'] = response.xpath('//input[@id="sid"]/@value').extract()
               </code>
              </div>
              <div class="line number20 index19 alt1">
               <code class="python spaces">
               </code>
               <code class="python comments">
                #i['name'] = response.xpath('//div[@id="name"]').extract()
               </code>
              </div>
              <div class="line number21 index20 alt2">
               <code class="python spaces">
               </code>
               <code class="python comments">
                #i['description'] = response.xpath('//div[@id="description"]').extract()
               </code>
              </div>
              <div class="line number22 index21 alt1">
               <code class="python spaces">
               </code>
               <code class="python keyword">
                return
               </code>
               <code class="python plain">
                i
               </code>
              </div>
             </div>
            </td>
           </tr>
          </tbody>
         </table>
        </div>
       </div>
       <p>
        我们只需要对这个样板做一些更新。
       </p>
       <h3>
        更新“start_urls”列表
       </h3>
       <p>
        首先，添加问题的第一个页面链接到start_urls列表：
       </p>
       <div>
        <div class="syntaxhighlighter notranslate python" id="highlighter_462225">
         <table border="0" cellpadding="0" cellspacing="0">
          <tbody>
           <tr>
            <td class="gutter">
             <div class="line number1 index0 alt2">
              1
             </div>
             <div class="line number2 index1 alt1">
              2
             </div>
             <div class="line number3 index2 alt2">
              3
             </div>
            </td>
            <td class="code">
             <div class="container">
              <div class="line number1 index0 alt2">
               <code class="python plain">
                start_urls
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                [
               </code>
              </div>
              <div class="line number2 index1 alt1">
               <code class="python spaces">
               </code>
               <code class="python string">
                'http://stackoverflow.com/questions?pagesize=50&amp;sort=newest'
               </code>
              </div>
              <div class="line number3 index2 alt2">
               <code class="python plain">
                ]
               </code>
              </div>
             </div>
            </td>
           </tr>
          </tbody>
         </table>
        </div>
       </div>
       <h3>
        更新“rules”列表
       </h3>
       <p>
        接下来，我们需要添加一个正则表达式到“rules”属性中，以此告诉爬虫在哪里可以找到下一个页面链接：
       </p>
       <div>
        <div class="syntaxhighlighter notranslate python" id="highlighter_966385">
         <table border="0" cellpadding="0" cellspacing="0">
          <tbody>
           <tr>
            <td class="gutter">
             <div class="line number1 index0 alt2">
              1
             </div>
             <div class="line number2 index1 alt1">
              2
             </div>
             <div class="line number3 index2 alt2">
              3
             </div>
             <div class="line number4 index3 alt1">
              4
             </div>
            </td>
            <td class="code">
             <div class="container">
              <div class="line number1 index0 alt2">
               <code class="python plain">
                rules
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                [
               </code>
              </div>
              <div class="line number2 index1 alt1">
               <code class="python spaces">
               </code>
               <code class="python plain">
                Rule(LinkExtractor(allow
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                r
               </code>
               <code class="python string">
                'questions?page=[0-9]&amp;sort=newest'
               </code>
               <code class="python plain">
                ),
               </code>
              </div>
              <div class="line number3 index2 alt2">
               <code class="python spaces">
               </code>
               <code class="python plain">
                callback
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python string">
                'parse_item'
               </code>
               <code class="python plain">
                , follow
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python color1">
                True
               </code>
               <code class="python plain">
                )
               </code>
              </div>
              <div class="line number4 index3 alt1">
               <code class="python plain">
                ]
               </code>
              </div>
             </div>
            </td>
           </tr>
          </tbody>
         </table>
        </div>
       </div>
       <p>
        现在爬虫能根据那些链接自动请求新的页面，并将响应传递给“parse_item”方法，以此来提取问题和对应的标题。
       </p>
       <p>
        如果你仔细查看的话，可以发现这个正则表达式限制了它只能爬取前9个网页，因为在这个demo中，我们不想爬取所有的176234个网页。
       </p>
       <h3>
        更新“parse_item”方法
       </h3>
       <p>
        现在我们只需编写如何使用xpath解析网页，这一点我们已经在上一篇教程中实现过了，所以直接复制过来。
       </p>
       <div>
        <div class="syntaxhighlighter notranslate python" id="highlighter_711721">
         <table border="0" cellpadding="0" cellspacing="0">
          <tbody>
           <tr>
            <td class="gutter">
             <div class="line number1 index0 alt2">
              1
             </div>
             <div class="line number2 index1 alt1">
              2
             </div>
             <div class="line number3 index2 alt2">
              3
             </div>
             <div class="line number4 index3 alt1">
              4
             </div>
             <div class="line number5 index4 alt2">
              5
             </div>
             <div class="line number6 index5 alt1">
              6
             </div>
             <div class="line number7 index6 alt2">
              7
             </div>
             <div class="line number8 index7 alt1">
              8
             </div>
             <div class="line number9 index8 alt2">
              9
             </div>
             <div class="line number10 index9 alt1">
              10
             </div>
            </td>
            <td class="code">
             <div class="container">
              <div class="line number1 index0 alt2">
               <code class="python keyword">
                def
               </code>
               <code class="python plain">
                parse_item(
               </code>
               <code class="python color1">
                self
               </code>
               <code class="python plain">
                , response):
               </code>
              </div>
              <div class="line number2 index1 alt1">
               <code class="python spaces">
               </code>
               <code class="python plain">
                questions
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                response.xpath(
               </code>
               <code class="python string">
                '//div[@class="summary"]/h3'
               </code>
               <code class="python plain">
                )
               </code>
              </div>
              <div class="line number3 index2 alt2">
              </div>
              <div class="line number4 index3 alt1">
               <code class="python spaces">
               </code>
               <code class="python keyword">
                for
               </code>
               <code class="python plain">
                question
               </code>
               <code class="python keyword">
                in
               </code>
               <code class="python plain">
                questions:
               </code>
              </div>
              <div class="line number5 index4 alt2">
               <code class="python spaces">
               </code>
               <code class="python plain">
                item
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                StackItem()
               </code>
              </div>
              <div class="line number6 index5 alt1">
               <code class="python spaces">
               </code>
               <code class="python plain">
                item[
               </code>
               <code class="python string">
                'url'
               </code>
               <code class="python plain">
                ]
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                question.xpath(
               </code>
              </div>
              <div class="line number7 index6 alt2">
               <code class="python spaces">
               </code>
               <code class="python string">
                'a[@class="question-hyperlink"]/@href'
               </code>
               <code class="python plain">
                ).extract()[
               </code>
               <code class="python value">
                0
               </code>
               <code class="python plain">
                ]
               </code>
              </div>
              <div class="line number8 index7 alt1">
               <code class="python spaces">
               </code>
               <code class="python plain">
                item[
               </code>
               <code class="python string">
                'title'
               </code>
               <code class="python plain">
                ]
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                question.xpath(
               </code>
              </div>
              <div class="line number9 index8 alt2">
               <code class="python spaces">
               </code>
               <code class="python string">
                'a[@class="question-hyperlink"]/text()'
               </code>
               <code class="python plain">
                ).extract()[
               </code>
               <code class="python value">
                0
               </code>
               <code class="python plain">
                ]
               </code>
              </div>
              <div class="line number10 index9 alt1">
               <code class="python spaces">
               </code>
               <code class="python keyword">
                yield
               </code>
               <code class="python plain">
                item
               </code>
              </div>
             </div>
            </td>
           </tr>
          </tbody>
         </table>
        </div>
       </div>
       <p>
        这就是为爬虫提供的解析代码，但是现在先不要启动它。
       </p>
       <h3>
        添加一个下载延迟
       </h3>
       <p>
        我们需要通过在settings.py文件中设定一个下载延迟来善待StackOverflow（和任何其他网站）。
       </p>
       <div>
        <div class="syntaxhighlighter notranslate python" id="highlighter_44224">
         <table border="0" cellpadding="0" cellspacing="0">
          <tbody>
           <tr>
            <td class="gutter">
             <div class="line number1 index0 alt2">
              1
             </div>
            </td>
            <td class="code">
             <div class="container">
              <div class="line number1 index0 alt2">
               <code class="python plain">
                DOWNLOAD_DELAY
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python value">
                5
               </code>
              </div>
             </div>
            </td>
           </tr>
          </tbody>
         </table>
        </div>
       </div>
       <p>
        这告诉爬虫需要在每两个发出的新请求之间等待5秒钟。你也很有必要做这样的限制，因为如果你不这么做的话，StackOverflow将会限制你的访问流量，如果你继续不加限制地爬取该网站，那么你的IP将会被禁止。所有，友好点—要像对待自己的网站一样对待任何你爬取的网站。
       </p>
       <p>
        现在只剩下一件事要考虑—存储数据。
       </p>
       <h2>
        MongoDB
       </h2>
       <p>
        上次我们仅仅下载了50个问题，但是因为这次我们要爬取更多的数据，所有我们希望避免向数据库中添加重复的问题。为了实现这一点，我们可以使用一个MongoDB的
        <a href="http://docs.mongodb.org/manual/reference/method/db.collection.update/#upsert-option" target="_blank">
         upsert
        </a>
        方法，它意味着如果一个问题已经存在数据库中，我们将更新它的标题；否则我们将新问题插入数据库中。
       </p>
       <p>
        修改我们前面定义的MongoDBPipeline：
       </p>
       <div>
        <div class="syntaxhighlighter notranslate python" id="highlighter_90588">
         <table border="0" cellpadding="0" cellspacing="0">
          <tbody>
           <tr>
            <td class="gutter">
             <div class="line number1 index0 alt2">
              1
             </div>
             <div class="line number2 index1 alt1">
              2
             </div>
             <div class="line number3 index2 alt2">
              3
             </div>
             <div class="line number4 index3 alt1">
              4
             </div>
             <div class="line number5 index4 alt2">
              5
             </div>
             <div class="line number6 index5 alt1">
              6
             </div>
             <div class="line number7 index6 alt2">
              7
             </div>
             <div class="line number8 index7 alt1">
              8
             </div>
             <div class="line number9 index8 alt2">
              9
             </div>
             <div class="line number10 index9 alt1">
              10
             </div>
             <div class="line number11 index10 alt2">
              11
             </div>
             <div class="line number12 index11 alt1">
              12
             </div>
             <div class="line number13 index12 alt2">
              13
             </div>
             <div class="line number14 index13 alt1">
              14
             </div>
             <div class="line number15 index14 alt2">
              15
             </div>
             <div class="line number16 index15 alt1">
              16
             </div>
             <div class="line number17 index16 alt2">
              17
             </div>
             <div class="line number18 index17 alt1">
              18
             </div>
            </td>
            <td class="code">
             <div class="container">
              <div class="line number1 index0 alt2">
               <code class="python keyword">
                class
               </code>
               <code class="python plain">
                MongoDBPipeline(
               </code>
               <code class="python functions">
                object
               </code>
               <code class="python plain">
                ):
               </code>
              </div>
              <div class="line number2 index1 alt1">
              </div>
              <div class="line number3 index2 alt2">
               <code class="python spaces">
               </code>
               <code class="python keyword">
                def
               </code>
               <code class="python plain">
                __init__(
               </code>
               <code class="python color1">
                self
               </code>
               <code class="python plain">
                ):
               </code>
              </div>
              <div class="line number4 index3 alt1">
               <code class="python spaces">
               </code>
               <code class="python plain">
                connection
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                pymongo.Connection(
               </code>
              </div>
              <div class="line number5 index4 alt2">
               <code class="python spaces">
               </code>
               <code class="python plain">
                settings[
               </code>
               <code class="python string">
                'MONGODB_SERVER'
               </code>
               <code class="python plain">
                ],
               </code>
              </div>
              <div class="line number6 index5 alt1">
               <code class="python spaces">
               </code>
               <code class="python plain">
                settings[
               </code>
               <code class="python string">
                'MONGODB_PORT'
               </code>
               <code class="python plain">
                ]
               </code>
              </div>
              <div class="line number7 index6 alt2">
               <code class="python spaces">
               </code>
               <code class="python plain">
                )
               </code>
              </div>
              <div class="line number8 index7 alt1">
               <code class="python spaces">
               </code>
               <code class="python plain">
                db
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                connection[settings[
               </code>
               <code class="python string">
                'MONGODB_DB'
               </code>
               <code class="python plain">
                ]]
               </code>
              </div>
              <div class="line number9 index8 alt2">
               <code class="python spaces">
               </code>
               <code class="python color1">
                self
               </code>
               <code class="python plain">
                .collection
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                db[settings[
               </code>
               <code class="python string">
                'MONGODB_COLLECTION'
               </code>
               <code class="python plain">
                ]]
               </code>
              </div>
              <div class="line number10 index9 alt1">
              </div>
              <div class="line number11 index10 alt2">
               <code class="python spaces">
               </code>
               <code class="python keyword">
                def
               </code>
               <code class="python plain">
                process_item(
               </code>
               <code class="python color1">
                self
               </code>
               <code class="python plain">
                , item, spider):
               </code>
              </div>
              <div class="line number12 index11 alt1">
               <code class="python spaces">
               </code>
               <code class="python keyword">
                for
               </code>
               <code class="python plain">
                data
               </code>
               <code class="python keyword">
                in
               </code>
               <code class="python plain">
                item:
               </code>
              </div>
              <div class="line number13 index12 alt2">
               <code class="python spaces">
               </code>
               <code class="python keyword">
                if
               </code>
               <code class="python keyword">
                not
               </code>
               <code class="python plain">
                data:
               </code>
              </div>
              <div class="line number14 index13 alt1">
               <code class="python spaces">
               </code>
               <code class="python keyword">
                raise
               </code>
               <code class="python plain">
                DropItem(
               </code>
               <code class="python string">
                "Missing data!"
               </code>
               <code class="python plain">
                )
               </code>
              </div>
              <div class="line number15 index14 alt2">
               <code class="python spaces">
               </code>
               <code class="python color1">
                self
               </code>
               <code class="python plain">
                .collection.update({
               </code>
               <code class="python string">
                'url'
               </code>
               <code class="python plain">
                : item[
               </code>
               <code class="python string">
                'url'
               </code>
               <code class="python plain">
                ]},
               </code>
               <code class="python functions">
                dict
               </code>
               <code class="python plain">
                (item), upsert
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python color1">
                True
               </code>
               <code class="python plain">
                )
               </code>
              </div>
              <div class="line number16 index15 alt1">
               <code class="python spaces">
               </code>
               <code class="python plain">
                log.msg(
               </code>
               <code class="python string">
                "Question added to MongoDB database!"
               </code>
               <code class="python plain">
                ,
               </code>
              </div>
              <div class="line number17 index16 alt2">
               <code class="python spaces">
               </code>
               <code class="python plain">
                level
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                log.DEBUG, spider
               </code>
               <code class="python keyword">
                =
               </code>
               <code class="python plain">
                spider)
               </code>
              </div>
              <div class="line number18 index17 alt1">
               <code class="python spaces">
               </code>
               <code class="python keyword">
                return
               </code>
               <code class="python plain">
                item
               </code>
              </div>
             </div>
            </td>
           </tr>
          </tbody>
         </table>
        </div>
       </div>
       <p>
        为简单起见，我们没有优化查询，也没有处理索引值，因为这不是一个生产环境。
       </p>
       <h2>
        测试
       </h2>
       <p>
        启动爬虫！
       </p>
       <div>
        <div class="syntaxhighlighter notranslate shell" id="highlighter_553087">
         <table border="0" cellpadding="0" cellspacing="0">
          <tbody>
           <tr>
            <td class="gutter">
             <div class="line number1 index0 alt2">
              1
             </div>
            </td>
            <td class="code">
             <div class="container">
              <div class="line number1 index0 alt2">
               <code class="shell plain">
                $ scrapy crawl questions
               </code>
              </div>
             </div>
            </td>
           </tr>
          </tbody>
         </table>
        </div>
       </div>
       <p>
        现在你可以坐下来，看着你的数据库渐渐充满数据。
       </p>
       <h2>
        结论
       </h2>
       <p>
        你可以从
        <a href="https://github.com/realpython/stack-spider/releases/tag/part2" target="_blank">
         Github库
        </a>
        下载整个源代码，也可以在下面评论或提问。
       </p>
       <p>
       </p>
       <blockquote>
        <p>
         翻译：
         <a href="http://python.jobbole.com/author/woosheep/">
          木羊
         </a>
        </p>
        <p>
         英文出处：
         <a href="https://realpython.com/blog/python/web-scraping-with-scrapy-and-mongodb/" target="_blank">
          realpython.com
         </a>
        </p>
        <p>
         文章出处：http://python.jobbole.com/81320/
        </p>
       </blockquote>
      </div>
      <div>
       <strong>
        注：转载文章均来自于公开网络，仅供学习使用，不会用于任何商业用途，如果侵犯到原作者的权益，请您与我们联系删除或者授权事宜，联系邮箱：contact@dataunion.org。转载数盟网站文章请注明原文章作者，否则产生的任何版权纠纷与数盟无关。
       </strong>
      </div>
      <!--content_text-->
      <div class="fenxian">
       <!-- JiaThis Button BEGIN -->
       <div class="jiathis_style_32x32">
        <p class="jiathis_button_weixin">
        </p>
        <p class="jiathis_button_tsina">
        </p>
        <p class="jiathis_button_qzone">
        </p>
        <p class="jiathis_button_cqq">
        </p>
        <p class="jiathis_button_tumblr">
        </p>
        <a class="jiathis jiathis_txt jtico jtico_jiathis" href="http://www.jiathis.com/share" target="_blank">
        </a>
        <p class="jiathis_counter_style">
        </p>
       </div>
       <!-- JiaThis Button END -->
      </div>
     </article>
     <!--content-->
     <!--相关文章-->
     <div class="xianguan">
      <div class="xianguantitle">
       相关文章！
      </div>
      <ul class="pic">
       <li>
        <a href="http://dataunion.org/20337.html">
         <img src="http://dataunion.org/wp-content/uploads/2015/08/t018da5f8c4955f422c_副本.jpg"/>
        </a>
        <a class="link" href="http://dataunion.org/20337.html" rel="bookmark" title="开源爬虫软件汇总！">
         开源爬虫软件汇总！
        </a>
       </li>
       <li>
        <a href="http://dataunion.org/17967.html">
         <img src="http://dataunion.org/wp-content/uploads/2015/05/t012629dcb871756775-300x154.jpg"/>
        </a>
        <a class="link" href="http://dataunion.org/17967.html" rel="bookmark" title="利用爬虫技术能做到哪些很酷、很有趣、很有用的事情？">
         利用爬虫技术能做到哪些很酷、很有趣、很有用的事情？
        </a>
       </li>
       <li>
        <a href="http://dataunion.org/16502.html">
         <img src="http://dataunion.org/wp-content/uploads/2015/04/34fe394aed2f4b7dc53cd7fbc7d3e472_副本.png"/>
        </a>
        <a class="link" href="http://dataunion.org/16502.html" rel="bookmark" title="Python爬虫手把手系列（四）：Cookie的使用">
         Python爬虫手把手系列（四）：Cookie的使用
        </a>
       </li>
       <li>
        <a href="http://dataunion.org/16499.html">
         <img src="http://dataunion.org/wp-content/uploads/2015/04/34fe394aed2f4b7dc53cd7fbc7d3e472_副本.png"/>
        </a>
        <a class="link" href="http://dataunion.org/16499.html" rel="bookmark" title="Python爬虫手把手系列（三）：URLError异常处理">
         Python爬虫手把手系列（三）：URLError异常处理
        </a>
       </li>
      </ul>
     </div>
     <!--相关文章-->
     <div class="comment" id="comments">
      <!-- You can start editing here. -->
      <!-- If comments are open, but there are no comments. -->
      <div class="title">
       期待你一针见血的评论，Come on！
      </div>
      <div id="respond">
       <p>
        不用想啦，马上
        <a href="http://dataunion.org/wp-login.php?redirect_to=http%3A%2F%2Fdataunion.org%2F16240.html">
         "登录"
        </a>
        发表自已的想法.
       </p>
      </div>
     </div>
     <!-- .nav-single -->
    </div>
    <!--Container End-->
    <aside id="sitebar">
     <div class="sitebar_list2">
      <div class="wptag">
       <span class="tagtitle">
        热门标签+
       </span>
       <div class="tagg">
        <ul class="menu" id="menu-%e5%8f%8b%e6%83%85%e9%93%be%e6%8e%a5">
         <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-1605" id="menu-item-1605">
          <a href="http://taidizh.com/">
           泰迪智慧
          </a>
         </li>
         <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-20884" id="menu-item-20884">
          <a href="http://www.transwarp.cn/">
           星环科技
          </a>
         </li>
         <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-3538" id="menu-item-3538">
          <a href="http://datall.org/">
           珈和遥感
          </a>
         </li>
         <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-20888" id="menu-item-20888">
          <a href="http://www.chinahadoop.cn/">
           小象学院
          </a>
         </li>
        </ul>
       </div>
      </div>
     </div>
     <div class="sitebar_list">
      <div class="textwidget">
       <div align="center">
        <a href="http://study.163.com/course/courseMain.htm?courseId=991022" target="_blank">
         <img src="http://dataunion.org/wp-content/uploads/2016/03/dv.jpg"/>
        </a>
       </div>
      </div>
     </div>
     <div class="sitebar_list">
      <h4 class="sitebar_title">
       文章分类
      </h4>
      <div class="tagcloud">
       <a class="tag-link-44" href="http://dataunion.org/category/industry/demo" style="font-size: 10.204724409449pt;" title="4个话题">
        Demo展示
       </a>
       <a class="tag-link-31" href="http://dataunion.org/category/experts" style="font-size: 15.826771653543pt;" title="52个话题">
        专家团队
       </a>
       <a class="tag-link-870" href="http://dataunion.org/category/tech/ai" style="font-size: 19.795275590551pt;" title="273个话题">
        人工智能
       </a>
       <a class="tag-link-488" href="http://dataunion.org/category/%e5%8a%a0%e5%85%a5%e6%95%b0%e7%9b%9f" style="font-size: 8pt;" title="1个话题">
        加入数盟
       </a>
       <a class="tag-link-869" href="http://dataunion.org/category/tech/viz" style="font-size: 17.204724409449pt;" title="93个话题">
        可视化
       </a>
       <a class="tag-link-30" href="http://dataunion.org/category/partners" style="font-size: 10.645669291339pt;" title="5个话题">
        合作伙伴
       </a>
       <a class="tag-link-889" href="http://dataunion.org/category/parterc" style="font-size: 11.582677165354pt;" title="8个话题">
        合作会议
       </a>
       <a class="tag-link-104" href="http://dataunion.org/category/books" style="font-size: 12.96062992126pt;" title="15个话题">
        图书
       </a>
       <a class="tag-link-220" href="http://dataunion.org/category/tech/base" style="font-size: 19.850393700787pt;" title="281个话题">
        基础架构
       </a>
       <a class="tag-link-219" href="http://dataunion.org/category/tech/analysis" style="font-size: 19.409448818898pt;" title="232个话题">
        数据分析
       </a>
       <a class="tag-link-887" href="http://dataunion.org/category/tech/dm" style="font-size: 13.291338582677pt;" title="17个话题">
        数据挖掘
       </a>
       <a class="tag-link-34" href="http://dataunion.org/category/tech" style="font-size: 20.732283464567pt;" title="404个话题">
        文章
       </a>
       <a class="tag-link-1" href="http://dataunion.org/category/uncategorized" style="font-size: 22pt;" title="693个话题">
        未分类
       </a>
       <a class="tag-link-4" href="http://dataunion.org/category/events" style="font-size: 14.503937007874pt;" title="29个话题">
        活动
       </a>
       <a class="tag-link-890" href="http://dataunion.org/category/tech/%e6%b7%b1%e5%ba%a6%e5%ad%a6%e4%b9%a0" style="font-size: 10.204724409449pt;" title="4个话题">
        深度学习
       </a>
       <a class="tag-link-221" href="http://dataunion.org/category/tech/devl" style="font-size: 18.968503937008pt;" title="193个话题">
        编程语言
       </a>
       <a class="tag-link-888" href="http://dataunion.org/category/career" style="font-size: 15.661417322835pt;" title="48个话题">
        职业规划
       </a>
       <a class="tag-link-5" href="http://dataunion.org/category/jobs" style="font-size: 14.11811023622pt;" title="25个话题">
        职位
       </a>
       <a class="tag-link-871" href="http://dataunion.org/category/industry" style="font-size: 15.716535433071pt;" title="49个话题">
        行业
       </a>
       <a class="tag-link-613" href="http://dataunion.org/category/industry/case" style="font-size: 16.984251968504pt;" title="84个话题">
        行业应用
       </a>
       <a class="tag-link-885" href="http://dataunion.org/category/industry/news" style="font-size: 17.425196850394pt;" title="102个话题">
        行业资讯
       </a>
       <a class="tag-link-10" href="http://dataunion.org/category/training" style="font-size: 14.228346456693pt;" title="26个话题">
        课程
       </a>
       <a class="tag-link-16" href="http://dataunion.org/category/sources" style="font-size: 15.661417322835pt;" title="48个话题">
        资源
       </a>
      </div>
     </div>
     <div class="sitebar_list">
      <h4 class="sitebar_title">
       功能
      </h4>
      <ul>
       <li>
        <a href="http://dataunion.org/wp-login.php?action=register">
         注册
        </a>
       </li>
       <li>
        <a href="http://dataunion.org/wp-login.php">
         登录
        </a>
       </li>
       <li>
        <a href="http://dataunion.org/feed">
         文章
         <abbr title="Really Simple Syndication">
          RSS
         </abbr>
        </a>
       </li>
       <li>
        <a href="http://dataunion.org/comments/feed">
         评论
         <abbr title="Really Simple Syndication">
          RSS
         </abbr>
        </a>
       </li>
       <li>
        <a href="https://cn.wordpress.org/" title="基于WordPress，一个优美、先进的个人信息发布平台。">
         WordPress.org
        </a>
       </li>
      </ul>
     </div>
    </aside>
    <div class="clear">
    </div>
   </div>
   <!--main-->
   ﻿
   <footer id="dibu">
    <div class="about">
     <div class="right">
      <ul class="menu" id="menu-%e5%ba%95%e9%83%a8%e8%8f%9c%e5%8d%95">
       <li class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-18024" id="menu-item-18024">
        <a href="http://dataunion.org/category/partners">
         合作伙伴
        </a>
       </li>
       <li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-20881" id="menu-item-20881">
        <a href="http://dataunion.org/contribute">
         文章投稿
        </a>
       </li>
       <li class="menu-item menu-item-type-taxonomy menu-item-object-category menu-item-20872" id="menu-item-20872">
        <a href="http://dataunion.org/category/%e5%8a%a0%e5%85%a5%e6%95%b0%e7%9b%9f">
         加入数盟
        </a>
       </li>
       <li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-22441" id="menu-item-22441">
        <a href="http://dataunion.org/f-links">
         友情链接
        </a>
       </li>
       <li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-20874" id="menu-item-20874">
        <a href="http://dataunion.org/aboutus">
         关于数盟
        </a>
       </li>
      </ul>
      <p class="banquan">
       数盟社区        ，
        做最棒的数据科学社区
      </p>
     </div>
     <div class="left">
      <ul class="bottomlist">
       <li>
        <a href="http://weibo.com/DataScientistUnion  " target="_blank" 　title="">
         <img src="http://dataunion.org/wp-content/themes/yzipi/images/weibo.png"/>
        </a>
       </li>
       <li>
        <a class="cd-popup-trigger" href="http://dataunion.org/16240.html#0">
         <img src="http://dataunion.org/wp-content/themes/yzipi/images/weixin.png"/>
        </a>
       </li>
      </ul>
      <div class="cd-popup">
       <div class="cd-popup-container">
        <h1>
         扫描二维码,加微信公众号
        </h1>
        <img src="http://dataunion.org/wp-content/themes/yzipi/images/2014-12-06-1515289049.png"/>
        <a class="cd-popup-close" href="http://dataunion.org/16240.html">
        </a>
       </div>
       <!-- cd-popup-container -->
      </div>
      <!-- cd-popup -->
     </div>
    </div>
    <!--about-->
    <div class="bottom">
     <a href="http://dataunion.org/">
      数盟社区
     </a>
     <a href="http://www.miitbeian.gov.cn/" rel="external nofollow" target="_blank">
      京ICP备14026740号
     </a>
     联系我们：
     <a href="mailto:contact@dataunion.org" target="_blank">
      contact@dataunion.org
     </a>
     <div class="tongji">
     </div>
     <!--bottom-->
     <div class="scroll" id="scroll" style="display:none;">
      ︿
     </div>
    </div>
   </footer>
   <!--dibu-->
  </div>
 </body>
</html>